﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using hedefgrup.reports.renault.definitions;
using hedefgrup.reports.renault;
using hedefgrup.reports.renault.calculators;
using hedefgrup.reports.renault.implementation;
using hedefgrup.reports.renault.date;
using System.Collections.Generic;
using System.Globalization;

public partial class dealerTargetResults : reportPage
{
    private const string SUMMARY_TABLE_HEADER_CELL_TEMPLATE = "<td width='30%' height=18px align=center class=t_head >{0}</td>";
    private const string SUMMARY_TABLE_VALUE_CELL_TEMPLATE = "<td width='70%' height=18px align='left' class=vktxt8 >{0}</td>";
    private const string REPORT_TABLE_HEADER_CELL_TEMPLATE = "<td width={0}px height=38px align=center class=t_head valign=center>{1}</td>";
    private const string REPORT_ROW_TEMPLATE = "<tr onmouseover='show(this)' onmouseout='sout(this)' >{0}</td>";
    private const string REPORT_CELL_TEMPLATE = "<td style='text-align:right;' class=vktxt8 >{0}</td>";
    private const string REPORT_FAILURE_CELL_TEMPLATE = "<td style='text-align:right;' class=vktxt10 >{0}</td>";
    private const string REPORT_SUCCESS_CELL_TEMPLATE = "<td style='text-align:right;' class=vktxt9 >{0}</td>";
    private const string REPORT_CELL_LEFT_ALIGNED_TEMPLATE = "<td class=vktxt8 >{0}</td>";

    private const string GRAPH_FORMAT = "<img src='/forms/common/graph3.aspx?s={0:00}{1:00}&e={2:00}{3:00}&g_n={4}&g_v={5}&g_v2={6}&g_s={7}' /><br /><br />";

    private static CultureInfo english = CultureInfo.GetCultureInfo("en-US");

    protected override string getReportFileName()
    {
        return "HEDEFLER - " + base.getReportFileName();
    }

    protected static string getCellTemplate(reportRowDefinition row, bool success)
    {
        return success ? REPORT_SUCCESS_CELL_TEMPLATE : REPORT_FAILURE_CELL_TEMPLATE;
    }

    private static string generateReportTableHeaderCell(string text, int width)
    {
        return string.Format(REPORT_TABLE_HEADER_CELL_TEMPLATE, width, text);
    }

    private static string generateReportTableHeaderCell(questionDefinition questionToReport, int width)
    {
        return generateReportTableHeaderCell(questionToReport.getCode() + " - " + questionToReport.getName(), width);
    }

    private static double getCompareValue(reportRowDefinition row)
    {
        return !string.IsNullOrEmpty(row.getAttributeByName("cv")) ? Convert.ToDouble(row.getAttributeByName("cv"), english) : 0;
    }

    private string generateReportTableRow(reportMonth[] monthsInInterval, reportRowDefinition row, reportDealerInfo dealerInfo, calculatorType calculationType)
    {
        if (dealerInfo.data.baseCount <= 0) return string.Empty;
        StringBuilder htmlBuilder = new StringBuilder();

        htmlBuilder.AppendFormat(REPORT_CELL_LEFT_ALIGNED_TEMPLATE, dealerInfo.dealer.getCode());
        htmlBuilder.AppendFormat(REPORT_CELL_LEFT_ALIGNED_TEMPLATE, dealerInfo.dealer.getName());

        foreach (reportMonth month in monthsInInterval)
        {
            dealerInfo = base.getCalculator().generateReportDataForSingleDealer(dealerInfo.dealer, calculationType, month - (cumulativeMonths - 1), month);
            switch (row.getRowType())
            {
                case "base":
                    htmlBuilder.AppendFormat(REPORT_CELL_TEMPLATE, dealerInfo.data.baseCount);
                    break;
                default:
                    double value = 0;
                    question questionToReport = dealerInfo.data.questions[row.getQuestionToReport()];
                    switch (row.getRowType())
                    {
                        case "percentage_of_option":
                            value = questionToReport.calculateOptionPercentage(Convert.ToInt32(row.getAttributeByName("o")));
                            break;
                        case Global.PROJECT_QVN:
                            value = questionToReport.calculateQvn();
                            break;
                        case "formula_1":
                            value = questionToReport.calculateFormula1();
                            break;
                        case "formula_2":
                            value = questionToReport.calculateFormula2();
                            break;
                        case "percentage_over_total_base":
                            string[] optionsToReport = row.getAttributeByName("o").Split(',');
                            foreach (string optionToReportString in optionsToReport)
                            {
                                int optionToReport = Convert.ToInt32(optionToReportString);
                                value += questionToReport.getOptionCount(optionToReport);
                            }
                            value = value / (double)dealerInfo.data.baseCount;
                            break;
                    }
                    double compareValue = getCompareValue(row);
                    value *= 100;
                    bool success = row.getAttributeByName("op") == ">" ? value >= compareValue : value <= compareValue;
                    htmlBuilder.AppendFormat(getCellTemplate(row, success), value.ToString("0.0"));
                    break;
            }
        }

        return string.Format(REPORT_ROW_TEMPLATE, htmlBuilder);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureUserIsLoggedIn();

        bool isGraphView = base.getString("v") == "graph";

        tableViewDiv.Visible = excelExportDiv.Visible = !isGraphView;
        if (excelExportDiv.Visible) excelExportDiv.Visible = !IsExcelDownloadRequest;

        excelReportName.Text = base.getReportFileName();

        reportDefinition reportDef = base.getDataCache().reportDefinitions["dealerTargets"];

        StringBuilder htmlBuilder = new StringBuilder();

        if (!isGraphView)
        {
            reportMonth[] monthsInInterval = reportMonth.getMonthsInInterval(startMonth, endMonth);
            int colspan = monthsInInterval.Length + 2;
            foreach (reportRowDefinition row in reportDef.rowDefinitions)
            {

                switch (row.getRowType())
                {
                    case "percentage_over_total_base":
                        htmlBuilder.AppendFormat("<tr><td colspan=\"{0}\" align=\"center\" class=\"t_head\" height=\"38px\"><b>{1}</b></td></tr>", colspan, row.getAttributeByName("h"));
                        break;
                    default:
                        questionDefinition questionToReport = base.getDataCache().questionDefinitions[row.getQuestionToReport()];
                        htmlBuilder.AppendFormat("<tr><td colspan=\"{0}\" align=\"center\" class=\"t_head\" height=\"38px\"><b>{1}</b></td></tr>", colspan, questionToReport.getCode() + " - " + questionToReport.getName());
                        break;
                }

                htmlBuilder.Append("<tr>");
                htmlBuilder.Append(generateReportTableHeaderCell("Kod", 40));
                htmlBuilder.Append(generateReportTableHeaderCell("Tanım", 220));

                foreach (reportMonth month in monthsInInterval)
                {
                    htmlBuilder.AppendFormat("<td class=t_head>{0} {1}</td>", month.getMonthName(), month.getYear());
                }

                htmlBuilder.Append("</tr>");

                dealerDefinition parentOfSelectedDealer = getDealerParent(targetDealer);

                List<reportDealerInfo> dealersToReport = new List<reportDealerInfo>
                (
                    base.getCalculator().generateReportDataForMultipleDealers(parentOfSelectedDealer, calculationType, startMonth - (cumulativeMonths - 1), startMonth)
                );

                bool doNotCheck = false;
                foreach (reportDealerInfo dlr in dealersToReport)
                {
                    doNotCheck = doNotCheck || dlr.dealer.Equals(parentOfSelectedDealer);
                    if (doNotCheck || dlr.dealer.Equals(targetDealer))
                    {
                        htmlBuilder.Append(generateReportTableRow(monthsInInterval, row, dlr, calculationType));
                    }
                }

                // reportTableHtml.Text = htmlBuilder.ToString();

                // htmlBuilder.AppendFormat(REPORT_CELL_LEFT_ALIGNED_TEMPLATE, dealerInfo.dealer.getCode());
                // htmlBuilder.AppendFormat(REPORT_CELL_LEFT_ALIGNED_TEMPLATE, dealerInfo.dealer.getName());

                htmlBuilder.AppendFormat("<tr><td height=\"38px\" colspan=\"{0}\" bgcolor=\"white\" >&nbsp;</td></tr>", colspan);


            }

            reportTableHtml.Text = htmlBuilder.ToString();
        }
        else
        {
            htmlBuilder.Append(generateGraph(targetDealer, base.startMonth - 11, base.startMonth, calculationType));
            graphicsContainer.Text = htmlBuilder.ToString();
        }

        base.RenderComplete();
        renderTime.Text = base.getElapsedRenderTime().ToString();
    }

    protected void Page_Load2(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureUserIsLoggedIn();

        bool isGraphView = base.getString("v") == "graph";
        tableViewDiv.Visible = excelExportDiv.Visible = !isGraphView;

        excelReportName.Text = base.getReportFileName();

        reportDefinition reportDef = base.getDataCache().reportDefinitions["dealerTargets"];

        StringBuilder htmlBuilder;

        if (!isGraphView)
        {
            htmlBuilder = new StringBuilder();

            htmlBuilder.Append(generateReportTableHeaderCell("Kod", 40));
            htmlBuilder.Append(generateReportTableHeaderCell("Tanım", 220));

            foreach (reportRowDefinition row in reportDef.rowDefinitions)
            {
                switch (row.getRowType())
                {
                    case "base":
                        htmlBuilder.Append(generateReportTableHeaderCell("Baz", 75));
                        break;
                    case "percentage_over_total_base":
                        htmlBuilder.Append(generateReportTableHeaderCell(row.getAttributeByName("h"), 120));
                        break;
                    default:
                        htmlBuilder.Append(generateReportTableHeaderCell(base.getDataCache().questionDefinitions[row.getQuestionToReport()], 120));
                        break;
                }
            }

            reportTableHeaderHtml.Text = htmlBuilder.ToString();
        }

        htmlBuilder = new StringBuilder();

        if (!isGraphView)
        {
            dealerDefinition parentOfSelectedDealer = getDealerParent(targetDealer);

            List<reportDealerInfo> dealersToReport = new List<reportDealerInfo>
            (
                base.getCalculator().generateReportDataForMultipleDealers(parentOfSelectedDealer, calculationType, base.startMonth - (cumulativeMonths - 1), base.startMonth)
            );

            bool doNotCheck = false;
            foreach (reportDealerInfo dlr in dealersToReport)
            {
                doNotCheck = doNotCheck || dlr.dealer.Equals(parentOfSelectedDealer);
                if (doNotCheck || dlr.dealer.Equals(targetDealer))
                {
                    // htmlBuilder.Append(generateReportTableRow(dlr, calculationType));
                }
            }

            reportTableHtml.Text = htmlBuilder.ToString();
        }
        else
        {
            htmlBuilder.Append(generateGraph(targetDealer, base.startMonth - 11, base.startMonth, calculationType));
            graphicsContainer.Text = htmlBuilder.ToString();
        }

        base.RenderComplete();
        renderTime.Text = base.getElapsedRenderTime().ToString();
    }

    private static double CalculateReportValue(reportDealerInfo reportForGraph, reportRowDefinition row, dealerDefinition targetDealer, calculatorType calculationType)
    {
        question questionToReport = reportForGraph.data.questions[row.getQuestionToReport()];

        switch (row.getRowType())
        {
            case "percentage_of_option":
                return questionToReport.calculateOptionPercentage(Convert.ToInt32(row.getAttributeByName("o")));
            case Global.PROJECT_QVN:
                return questionToReport.calculateQvn();
            case "formula_1":
                return questionToReport.calculateFormula1();
            case "formula_2":
                return questionToReport.calculateFormula2();
            case "percentage_over_total_base":
                double value = 0;
                string[] optionsToReport = row.getAttributeByName("o").Split(',');
                foreach (string optionToReportString in optionsToReport)
                {
                    int optionToReport = Convert.ToInt32(optionToReportString);
                    value += questionToReport.getOptionCount(optionToReport);
                }
                return value / (double)reportForGraph.data.baseCount;
        }

        return 0;
    }

    private string generateGraphString(reportRowDefinition row, dealerDefinition targetDealer, reportMonth startMonth, reportMonth endMonth, calculatorType calculationType, int cumulativeMonths)
    {
        StringBuilder graphString = new StringBuilder();
        foreach (reportMonth month in reportMonth.getMonthsInInterval(startMonth, endMonth))
        {
            reportDealerInfo reportForGraph = base.getCalculator().generateReportDataForSingleDealer(targetDealer, calculationType, month - (cumulativeMonths - 1), month);

            switch (row.getRowType())
            {
                case "base":
                    break;
                default:
                    double value = CalculateReportValue(reportForGraph, row, targetDealer, calculationType);
                    graphString.Append((value * 100).ToString("#.00", english) + "|");
                    break;
            }
        }
        graphString.Length -= 1;
        return graphString.ToString();
    }

    private string generateGraph(dealerDefinition targetDealer, reportMonth startMonth, reportMonth endMonth, calculatorType calculationType)
    {
        StringBuilder allGraphString = new StringBuilder();

        reportDefinition reportDef = base.getDataCache().reportDefinitions["dealerTargets"];

        foreach (reportRowDefinition row in reportDef.rowDefinitions)
        {
            string mapName = row.getRowType() == "percentage_over_total_base" ? row.getAttributeByName("h") : base.getDataCache().questionDefinitions[row.getQuestionToReport()].getName();

            allGraphString.AppendFormat("<table width=\"520\" border=\"1\"><tr><th colspan=\"13\">{0}</th></tr><tr>", mapName);
            allGraphString.Append("<td />");

            for (int i = 11; i >= 0; i--)
            {
                reportMonth r = base.startMonth - i;
                allGraphString.AppendFormat("<td align=\"center\">{0}<br />{1}</td>", r.getMonthName(), r.getYear());
            }

            allGraphString.Append("</tr>");

            for (int cType = 0; cType < 2; cType++)
            {
                allGraphString.Append("<tr><td>" + (cType == 0 ? "AYLIK" : "YILLIK"));

                for (int i = 11; i >= 0; i--)
                {
                    reportMonth month = base.startMonth - i;

                    reportDealerInfo reportForGraph = base.getCalculator().generateReportDataForSingleDealer(targetDealer, calculationType, cType == 0 ? month : month - 11, month);

                    allGraphString.AppendFormat("<td align=\"center\">{0:#.0}</td>", CalculateReportValue(reportForGraph, row, targetDealer, calculationType) * 100);
                }

                allGraphString.Append("</tr>");
            }
            allGraphString.Append("</table>");

            allGraphString.AppendFormat
            (
                GRAPH_FORMAT,
                startMonth.getYear(),
                startMonth.getMonth(),
                endMonth.getYear(),
                endMonth.getMonth(),
                (row.getRowType() == "percentage_over_total_base" ? row.getAttributeByName("h") : base.getDataCache().questionDefinitions[row.getQuestionToReport()].getName()),
                generateGraphString(row, targetDealer, startMonth, endMonth, calculationType, 1),
                generateGraphString(row, targetDealer, startMonth, endMonth, calculationType, 12),
                targetDealer.getCode() + " - " + targetDealer.getName()
            );
        }

        return allGraphString.ToString();
    }

    private dealerDefinition getDealerParent(dealerDefinition dealer)
    {
        return base.getDataCache().getDealer(dealer.getAttributeByName("parent"));
    }
}
